<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<style type="text/css">
			.mui-content {
				margin-bottom: 70px
			}
		</style>
		<link href="../../css/app.css" rel="stylesheet" />
		<link href="../../cssmui/mui.min.css" rel="stylesheet" />
		<link href="../../css/mylist.css" rel="stylesheet" />
		<script src="../../js/vue.min.js"></script>
		<script src="../../mui/mui.min.js"></script>
		<script src="../../js/app.js"></script>

		<script src="../../js/jsondb.js"></script>
		<script src="../../js/map/mydict.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../js/map/ioservices.js"></script>
		<script src="../../js/map/dictservice.js"></script>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-back mui-pull-left"></a>
			<a id="bt_cust" class=" mui-btn mui-btn-link mui-pull-right">选交易方</a>
			<h1 class="mui-title">销售单</h1>
		</header>

		<div class="mui-content">

			<div class="mui-card mui-card-content mui-card-content-inner  mui-row" style="height:80px">
				<div class="subscript">点 </div>
				<span class="mui-col-sm-3 mui-col-xs-3 "> 单号：</span>
				<span class="mui-col-sm-9 mui-col-xs-9 text_content "> {{card.pid||'新增单据(自动编号)'}}【{{card.status|status2text}}】 </span>
				<span class="mui-col-sm-3 mui-col-xs-3 "> 姓名：</span>
				<span id="uname" class="mui-col-sm-9 mui-col-xs-9 text_content ">{{card.uname||'请选择交易对象'}}({{convertULevel(card.clevel)}})</span>
				<span id="tel" class="mui-col-sm-3 mui-col-xs-3 "> 联系方式：</span>
				<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{card.联系方式||'无'}}</span>
				<span class="mui-col-sm-3 mui-col-xs-3 "> 下单时间：</span>
				<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{card.sdate||'保存后显示'}}</span>
				<span id="fhsj" class="mui-col-sm-3 mui-col-xs-3 "> 发货时间：</span>
				<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{card.edate||'发货后显示'}}</span>
				<span class="mui-col-sm-3 mui-col-xs-3 "> 总重量：</span>
				<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{card.allweight}}kg</span>
				<span class="mui-col-sm-3 mui-col-xs-3 "> 总体积：</span>
				<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{card.allsize}}立方</span>
				<span class="mui-col-sm-3 mui-col-xs-3 "> 总件数：</span>
				<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{card.allnum}}</span>
				<span class="mui-col-sm-3 mui-col-xs-3 "> 品种数：</span>
				<span class="mui-col-sm-3 mui-col-xs-3 text_content ">{{card.tpnum}}</span>
				<span id="fhdz" class="mui-col-sm-3 mui-col-xs-3 "> 对方地址：</span>
				<span class="mui-col-sm-9 mui-col-xs-9 text_content ">{{card.地址}}</span>
				<span class="mui-col-sm-12 mui-col-xs-12  ">备注</span>
				<textarea id="textarea" rows="2" v-model="card.remark" style="margin-bottom:0px;padding:1px" placeholder="填写对方特殊要求">
					</textarea>

			</div>
			<form class="mui-input-group ">
				<div class="mui-input-row " style="background-color:beige; ">
					<label>单据总额：</label>
					<input type="number" v-model="card.amount" class="mui-input-clear " readonly>
				</div>
				<div class="mui-input-row " style="background-color:beige; ">
					<button v-if="card.status>2" class="paybtn mui-pull-right " style="background-color: #DDFFDD;margin-top:3px ;margin-right:10px">去结算</button>
				</div>
			</form>

			<ul class="mui-table-view ">

				<li v-for="r in list" style="padding:6px" class="mui-table-view-cell mui-media " @click="opdetail(r._idkey)">

					<img class=" mui-pull-left img80 " :src="r.gimg[0]|src">
					<div class="mui-media-body">
						<p class="">{{r.gname}} </p>
						<p class="">商品编号 [{{r.gid}}]</p>
						<p class="">数量:<span class="">{{r.num}}</span>, 单价:
							<span class="">￥{{r.price}}</span></p>
						<div class='mui-ellipsis-2'>
							金额:<span class="">￥{{r.price*r.num}}</span>
						</div>
					</div>
				</li>
			</ul>

		</div>
		<nav class="mui-bar mui-bar-tab">
			<a class="mui-tab-item" href="copy">
				<span class="mui-tab-label">COPY</span>
			</a>
			<a id="newsubbtn" class="mui-tab-item" style="color:#606060" href="newsub">
				<span class="mui-tab-label">+明细</span>
			</a>
			<a class="mui-tab-item prevbtn" href="previous">
				<span class="mui-tab-label">撤销</span>
			</a>
			<a class="mui-tab-item nextbtn" href="next">
				<span class="mui-tab-label">保存</span>
			</a>

		</nav>

		<script type="text/javascript">
			var _PORS = 's1';
			var _titleconfig = [];
			//"0 作废，1 草稿，2)制定计划:出库/入库,3)审核后发货/签收 转财务记账,4)归档|转入历史表,注：付款流程不在此流程中"
			var _status = ['已作废', '草拟中', '已制单', '已签收', '已归档'];
			//-------------定义
			var _tb_io = new XCDBHelp('tb_io')
			var _tb_io1 = new XCDBHelp('tb_io1')
			var _tb_contacts = new XCDBHelp('tb_contacts')
			var _tb_goods = new XCDBHelp('tb_goods')
			var _goodrs = null;
			var _vu = null; //当前vue模版
			var _vu2 = null; //当前vue模版
			var targetTab = ['contact_list.html', 'io1_itemp.html', 'acc_item.html'];
			var _curmd = null; //当前的模版
			var _subrs2 = null; // some _curmd2 in _subrs2
			//	var _pros_=0;//当前
			var _mould = { //默认模版,用于恢复
				pid: null,
				cid: '', //联系人id
				pors: '', //交易类型 1采购
				amount: 0, //总价
				reduce: 0, //核减
				tpnum: 0, //品种数
				allnum: 0, //件数
				allsize: 0, //件数
				allweight: 0, //重量
				sdate: new Date().Format(), //下单时间
				edate: '', //签收时间
				remark: '', //备注
				status: 1,
				联系方式: '',
				uname: '',
				clevel: '',
				地址: ''
			};

			function setBtncss(val) {
				var prevbtn = document.querySelector('.prevbtn').querySelector('span')
				if(val == 1) {
					prevbtn.innerText = '作废';
					prevbtn.style.color = '#909090';
				} else if(val == 0) {
					prevbtn.innerText = '删除';
					prevbtn.style.color = '#909090';
				} else if(val == 2) {
					prevbtn.innerText = '撤销';
					prevbtn.style.color = '#909090';
				} else {
					prevbtn.innerText = '';
					prevbtn.style.color = '#a0a0a0';
				}
				var nextbtn = document.querySelector('.nextbtn').querySelector('span')
				if(val == 2) {
					nextbtn.innerText = _titleconfig[0];
					nextbtn.style.color = '#909090';
				} else if(val == 1) {
					nextbtn.innerText = '保存';
					nextbtn.style.color = '#909090';
				} else if(val == 0) {
					nextbtn.innerText = '恢复';
					nextbtn.style.color = '#909090';
				} else if(val == 3) {
					nextbtn.innerText = '归档';
					nextbtn.style.color = '#909090';
				} else {
					nextbtn.innerText = '';
					nextbtn.style.color = '#a0a0a0';
				}

			}
			//-----------------初始化-----------
			//					if(ISDEVELOP == '1') { //开发模式下启用
			//						createMd();
			//					}
			//-------------监听事件----------
			//监听数据改变的事件,选择供应商以后会改变部分字段

			//------------按钮事件--------------	

			mui.ready(function() {
				//底部按钮
				//	mui.init();
				mui("nav").on("tap", ".mui-tab-item", function() {
					var eventname = this.getAttribute("href")
					blur();
					if(eventname == "newsub") { //新增明细
						newsub();
					} else if(eventname == "next") {
						if(_curmd.status == 2) {
							mui.confirm('注意:一旦确认' + _titleconfig[0] + '无法撤销!,确定要' + _titleconfig[0] + '吗?', '', ['否', '是'], function(e) {
								if(e.index == 1) {
									_curmd.status = 3;
								}
							})
						} else if(_curmd.status == 3) {
							mui.confirm('注意:一旦归档,单据只能在历史列表中才能查看,继续归档吗?', '', ['否', '是'], function(e) {
								if(e.index == 1) {
									_curmd.status = 4;
								}
							})
						} else {
							if(_curmd.status < 3)
								_curmd.status = parseInt(_curmd.status) + 1;
						}
					} else if(eventname == "previous") {
						if(_curmd.status <= 1) {
							if(_subrs2 && _subrs2.length > 0) {
								mui.alert('请删除明细后作废单据');
								return;
							}
							if(_curmd.pid) {
								mui.confirm('警告!', '你确定要作废当前单据吗', ['否', '是'], function(e) {
									if(e.index == 1) {
										//如果没有明细,删除当前单据编号的数据
										if(_subrs2 == null || _subrs2.length == 0) {
											_tb_io.delObjById(_curmd.pid)
											_reload = 'list';
											mui.back();
										} else {
											_curmd.status = 0;
										}
									}
								});
							}
						} else if(_curmd.status > 0 && _curmd.status < 3)
							_curmd.status = parseInt(_curmd.status) - 1;
					} else if(eventname == "copy") {
						mui.confirm('你要新建一份同样内容的单据吗', '', ['否', '是'], function(e) {
							if(e.index == 1) {
								copy();
								mui.toast("单据已经copy,数据与原单据一致");
							}
						});
					}
				});
				window.addEventListener('bechanged', function(e) {　 //获取参数值					
					if(e.detail.reload == 'contact') { //供应商发生改变
						//alert('xxx')
						//log(e.detail.data, 'purchase_item.html105')
						var data = e.detail.data;
						_curmd.cid = data._idkey;
						_curmd.uname = data.uname;
						_curmd.clevel = data.clevel;
						_curmd.联系方式 = data.tel;
						_curmd.地址 = data.addr;
					} else if(e.detail.reload == 'itemp') //更新明细列表
					{
						step2();
					}
				});
				//去结算按钮

				//打开供应商选择列表
				mui('.mui-bar-nav').on('tap', '#bt_cust', function(e) {
					//联系人选择
					var i = (_PORS == 'b1' || _PORS == 'rb1') ? 1 : 2;
					open(targetTab[0], {
						target: 'sel',
						group: i
					});
				});

			});
			//添加明细
			function newsub() {
				blur();
				if(_curmd.status > 1) {
					mui.alert('单据已保存,无法添加明细')
					return;
				}

				//清空数据和key
				if(save() == false) return;
				//商品明细
				open(targetTab[1], {
					pid: _curmd.pid, //save是 赋值
					cid: _curmd.cid,
					pors: _curmd.pors
				});
			}

			//-----------plus设备初始化准备--------------
			//初始化回调
			function afterPlusReady() {
				mui.init();
				var self = _self;
				//console.log(self.pors)
				if(self.pors)
					setPors(self.pors);

				//载入有效商品数据
				_goodrs = _tb_goods.where({
					status: '1'
				}).getList();
				_goodrs = _AW.select(_goodrs, "_idkey gid,gname,gclass,spec,gimg,quality")

				//console.log(self.selectedid)
				//if(!self.pros) return;
				//_pros_=self.pros;
				if(self.selectedid) { //编辑		//通过id载入数据	
					var rc = _tb_io.getObjByID(self.selectedid)
					if(rc) {
						step1(rc)
					}
				} else { //新增
					step1()

				}

			}

			function setPors(p) {
				//console.log(p);
				_mould.pors = _PORS = p;

				switch(_PORS) {
					case 'b1':
						_titleconfig = ['签收', '采购单', '收货时间', 'b1', '采购金额'];
						_status[3] = '已签收'
						break;
					case 's1':
						_titleconfig = ['发货', '销售单', '发货时间', 's1', '销售金额'];
						_status[3] = '已发货'
						break;
					case 'rb1':
						_titleconfig = ['退货', '采购退货单', '发货时间', 'rb1', '退货金额'];
						_status[3] = '已退货'
						break;
					case 'rs1':
						_titleconfig = ['签收', '销售退货单', '收货时间', 'rs1', '退货金额'];
						_status[3] = '已签收'
						break;
				}

				mui('header .mui-title')[0].innerHTML = _titleconfig[1];
				G('fhsj').innerHTML = _titleconfig[2];

			}
			/////////////移动终端环境下的初始化

			//---------------计算---------------
			//数量改变计算总金额
			function detail2count() {
				//总价值,总体积,总数量,总重量,品种数
				var amount = 0,
					allsize = 0,
					allnum = 0,
					allweight = 0,
					tparr = [];
				if(_subrs2) {
					for(var i = 0; i < _subrs2.length; i++) {
						var detail = _subrs2[i]
						//console.log('damount'+detail.damount)
						amount += round2(detail.damount, 2);
						allsize += round2(detail.size, 2);
						allnum += round2(detail.num, 2);
						allweight += round2(detail.weight, 2);
						if('gclass' in detail) {
							tparr.push(detail.gclass);
						}
					}
				}
				//console.log('amount'+amount)
				_curmd.amount = round2(amount, 2);

				//	console.log("_curmd="+_curmd.amount)
				_curmd.allsize = round2(allsize, 2);
				_curmd.allnum = round2(allnum, 2);
				_curmd.allweight = round2(allweight, 2);
				if(tparr.length > 0) {
					_curmd.tpnum = arrDistinct(tparr).length
				}
			}
			//------------------持久化操作-----------------
			//、。。。。。。。。。读取。。。。。。。

			//读取保存的数据bind card 模版
			function step1(data) {
				//createR1(); //创建一个新的对象 用于存放数据
				_curmd = clone(_mould);
				if(data) { //如果数据不为空,写入对象
					_curmd.pid = data._idkey;
					_curmd.cid = data.cid;
					//console.log(JSON.stringify(data));
					if(data.cid) {
						var contact = _tb_contacts.getObjByID(data.cid)
						if(contact) {
							_curmd.uname = contact.uname;
							_curmd.联系方式 = contact.tel;
							_curmd.clevel = contact.clevel;
							_curmd.地址 = contact.addr;
						}
					}
					//{{convertULevel(clevel)}}

					_curmd.pors = data.pors;
					_curmd.reduce = data.reduce;
					_curmd.tpnum = parseInt(data.tpnum);
					_curmd.allnum = parseInt(data.allnum);
					_curmd.allweight = data.allweight;
					_curmd.sdate = data.sdate;
					_curmd.edate = data.edate;
					_curmd.remark = data.remark;
					_curmd.status = parseInt(data.status);
					setBtncss(_curmd.status);
				} else {
					_curmd.pid = null;
				} //bind模板

				//卡片缩小事件
				step2();

			}

			//读取明细模型 绑定明细模版
			//注意单据明细是在itemp 页面保存的,
			function step2() {
				//console.log(_curmd.pid);
				if(_curmd.pid) { //查询主表id对应的明细数据
					//查询主表的明细记录
					var rs = _tb_io1.where({
						pid: _curmd.pid
					}).getList();

					//左联接商品表,载入图片
					_subrs2 = _AW.leftjoin(rs, _goodrs, 'gid=gid');
					for(var i = 0; i < _subrs2.length; i++) {
						var detail = _subrs2[i]
						if(detail.gimg == null || detail.gimg.length == 0) continue;
						//重新设定为第一张图片路径???

					}
				} else {
					_subrs2 = null;
				}
				//计算合计价格和重量
				detail2count();
				//	console.log(_vu)
				if(_vu == null)
					bindVue();
				else {
					_vu.list = _subrs2;
				}

			}

			function bindVue() {
				//console.log("zuantai:"+_curmd.status);
				Vue.filter('src', function(value) {
					if(value) return value.src;
					return '';
				});
				Vue.filter('status2text', function(value) {
					return _status[value];
				});
				//console.log(JSON.stringify(_subrs2));
				_vu = new Vue({
					el: '.mui-content',
					data: {
						card: _curmd,
						list: _subrs2
					},
					methods: {
						opdetail: function(ee) {
							//console.log('tap:' + ee)
							open(targetTab[1], {
								selectedid: ee,
								pstatus: _curmd.status,
								pors: _curmd.pors,
								cid: _curmd.cid
							});
						},
						convertULevel: function(id) {
							//getDictText(getDictUlevel(),1)
							//	console.log("kkk"+id)
							return getDictText(getDictUlevel(), id);
						}
					},
					mounted: function() {
						mui(".mui-content").on('tap', '.subscript', function(e) {
							var t = this.parentNode;
							if(t.style.height == "")
								t.style.height = "80px";
							else
								t.style.height = "";
						});
						mui('.mui-content').on('tap', '.paybtn', function(e) {
							//acc_item
							//去结算

							console.log(targetTab[2])
							open(targetTab[2], {
								pors: _PORS,
								contact: _curmd.cid
							}); //target: 'sel',

						});
					}
				});

				_vu.$watch("card.status", function(val, oldval) {
					blur();
					//console.log(_curmd.status+' '+val);						
					save();
					if(val == 2) {
						mui.toast("保存完毕");
					} else if(val == 3) {
						//增加库存	
						////增加应付货款 	//增加应付货款 
						_IOM.iostock(_curmd, _subrs2);
						mui.toast(_titleconfig[0] + "完毕");
					} else if(oldval == 0) {
						mui.toast("已作废");
					}
					setBtncss(val);
				});

			}
			//。。。。。。。。。。写入。。。。。。。。。。。
			function save() {
				var data = {}
				if(_curmd.cid == null || _curmd.cid == '') {
					mui.alert('请选择交易对象');
					return false;
				}
				data._idkey = _curmd.pid;
				data.cid = _curmd.cid;
				data.pors = _curmd.pors;
				data.amount = round2(_curmd.amount, 2);
				data.reduce = round2(_curmd.reduce, 2);
				data.tpnum = _curmd.tpnum;
				data.allnum = _curmd.allnum;
				data.allsize = round2(_curmd.allsize, 2);
				data.allweight = round2(_curmd.allweight, 2);
				data.sdate = _curmd.sdate;
				if(_curmd.status == 3)
					_curmd.edate = new Date().Format(); //重新格式化	
				else if(_curmd.status < 3)
					_curmd.edate = '';
				data.edate = _curmd.edate;
				data.remark = _curmd.remark;
				data.status = _curmd.status;
				_curmd.pid = _tb_io.setObj(data);
				if(_reload == 'copy')
					copydetail();
				//console.log(_curmd.pid )
				_reload = 'list';
				return true;
			}
			//同样的商品再下一单
			function copy() {
				_curmd.pid = null;
				_curmd.sdate = new Date().Format();
				_curmd.edate = null;
				_curmd.remark = '';
				_reload = 'copy';
				_curmd.status = 1; //修改状态自动保存单据
				//save（）
			}

			function copydetail() {
				console.log('copy()' + _curmd.pid)
				if(_curmd.pid) {
					//copy 明细
					for(var i = 0; i < _subrs2.length; i++) {
						var data = clone(_subrs2[i]);
						data._idkey = data.did = null;
						data.pid = _curmd.pid;
						_tb_io1.setObj(data);
					}
					//重新读取明细更新_subrs2
					step2();
				}
			}
		</script>
	</body>

</html>